<?php

namespace app\dao\exam;

use app\dao\BaseDao;
use app\model\exam\ExamPaper;
use app\model\exam\ExamQuestion;
use think\Exception;

class ExamPaperDao extends BaseDao
{

    public function index(array $where)
    {
        return $this->getModel()->withSearch(['title', 'pattern'], ['title' => $where['title'], 'pattern' => $where['pattern']])
            ->where('website_id', $where['website_id'])->order('id', 'desc')->paginate($where['pageSize']);
    }

    public function create(array $where)
    {
        unset($where['id']);
        return $this->getModel()->create($where);
    }

    public function updateDao(array $where)
    {
        unset($where['website_id']);

        return $this->getModel()->update($where);
    }

    public function deleteDao(array $where)
    {
        return $this->getModel()->whereIn('id', $where['id'])->update(['delete_time' => date('Y-m-d H:i:s', time())]);
    }

    public function searchPaperTopic(array $where)
    {
        $data = $this->getModel()->find($where['id']);
        if ($data) {
            return (new ExamQuestion())->withoutField('create_time,delete_time,update_time,website_id')->order('type', 'asc')->select(explode(',', $data['questions']));
        }
    }

    protected function setModel(): string
    {
        return ExamPaper::class;
    }

    //-------------------------------------------api------------------------------------------------------------------

    /*
     * 测评题目
     */
    public function getSubject(array $where)
    {
        try {
            $data = $this->getModel()
                ->where('website_id', $where['website_id'])
                ->where('id', $where['id'])
                ->withoutField(['create_time', 'update_time', 'delete_time', 'page', 'page_size'])
                ->find();
            $arr = explode(',', $data['questions']);
            $ques = ExamQuestion::whereIn('id', $arr)
                ->withoutField(['start_time' . 'end_time', 'create_time', 'update_time', 'delete_time'])
                ->select();
            $data['data'] = $ques;
            $data['start_time'] = date('Y-m-d H:i:s');
            /**
             * time 1000 * 60 * 10 为10分钟检测一次
             * timesNum 最多可以违规几次
             */
            $data['other'] = ['time' => 1000 * 60 * 10, 'timesNum' => 6];
            unset($data['questions']);
            return $data;
        } catch (Exception $exception) {
            return null;
        }

    }
}